/**
 * promise.race 并发控制
 * max 最大并发量
 * pool 并发池
 */

let urls = ["a.com", "b.com", "c.com", "d.com", "e.com", "f.com"];
let max = 4;
let pool = [];

function request(url) {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve(`任务${url}完成`);
    }, 5000);
  }).then((res) => {
    console.log(res, "执行外部逻辑");
  });
}

// 添加任务
function addTask(url) {
  let task = request(url);
  pool.push(task);
  task.then((res) => {
    pool.splice(pool.indexOf(task), 1);
    console.log(`${url} 结束，当前并发数：${pool.length}`);
    // 如果还存在任务，则添加到并发队列
    // if(urls.length > 0){
    //   addTask(urls.shift())
    // }
  });
}

function run(race) {
  race.then((res) => {
    if (urls.length > 0) {
      addTask(urls.shift());
      run(Promise.race(pool));
    }
  });
}

while (pool.length < max) {
  let url = urls.shift();
  addTask(url);
}

let race = Promise.race(pool);
run(race);
